package queryid

import (
	"errors"
	"io/ioutil"
	"net/http"

	"gitee.com/hlwqds/clientSimulation/src/lib/lg"
	"gitee.com/hlwqds/clientSimulation/src/lib/myjson"
	"github.com/go-redis/redis"
	"github.com/tidwall/gjson"
)

//ReqPriD 处理请求的私有数据
type ReqPriD struct {
	Rdb      *redis.Client
	Logger   lg.Logger
	LogLevel lg.LogLevel
}

type rspStructResponse struct {
	Retcode  int    `json:"retcode"`
	Reason   string `json:"reason"`
	Response string `json:"response"`
}

type rspStruct struct {
	Response rspStructResponse `json:"response"`
}

func (p *ReqPriD) HandleCallPushAPIReuqest(w http.ResponseWriter, r *http.Request) {
	//time.Sleep(1 * time.Second)
	p.HandleAPIReuqest(w, r)
}

//HandleAPIReuqest 处理api的推送
func (p *ReqPriD) HandleAPIReuqest(w http.ResponseWriter, r *http.Request) {
	var data, httpRsp []byte
	var err error
	var retcode int
	var reason string

	data, err = ioutil.ReadAll(r.Body)
	if err != nil {
		retcode = errorCodeBufError
		reason = "read error"
		goto _error
	}
	p.logf(LOG_INFO, "Api Reuqest Data:%s", data)

	httpRsp, err = p.iDQueryMoudleEntry(data)
	if err != nil {
		retcode = errorCodeHandleError
		reason = err.Error()
		goto _error
	} else {
		retcode = errorCodeNoError
		reason = "success"
		goto _exit
	}

_error:
	p.logf(LOG_ERROR, "retcode: %d, reason: %s", retcode, reason)

	httpRsp, err = p.GenErrorResp()
	if err != nil {
		http.Error(w, "GenErrorResp error", http.StatusExpectationFailed)
		return
	}
	goto _exit

_exit:
	p.logf(LOG_INFO, "retcode:%d, reason:%s", retcode, reason)

	w.Write(httpRsp)
	p.logf(LOG_INFO, "Response Data:%s", httpRsp)

	return
}

//IDQueryMoudleEntry 业务处理接口入口。返回json结构的字符串
func (p *ReqPriD) iDQueryMoudleEntry(req []byte) (rsp []byte, err error) {
	var callTypeInt, typeInt int64
	callTypeInt = gjson.GetBytes(req, myjson.GenPathForGJSON(jsonKeyRequest, jsonKeyCallType)).Int()

	typeInt = gjson.GetBytes(req, myjson.GenPathForGJSON(jsonKeyRequest, jsonKeyType)).Int()

	if callTypeInt == typeQueryCalledWithVOld || callTypeInt == typeQueryCalledOld {
		rsp, err = p.handleCalledOldQuery(req)
		if err != nil {
			goto _exit
		}
	} else {
		p.logf(LOG_INFO, "ivr type:%d", typeInt)

		switch typeInt {
		case typeKeyBackIVRQuery:
			rsp, err = p.handleKeyBackQuery(req)
			if err != nil {
				goto _exit
			}
			break
		case typeIVRQueryCalled:
			rsp, err = p.handleIVRQueryCalled(req)
			if err != nil {
				goto _exit
			}
			break
		case typeCommonIVRQuery:
			rsp, err = p.handleCommonIVRQuery(req)
			if err != nil {
				goto _exit
			}
			break
		default:
			err = errors.New("unknow type, maybe the common push")
			goto _exit
		}
	}

_exit:
	return rsp, err
}
